'use strict';


module.exports = class extends think.Controller {
	
	//登陆
	async signinAction(){
		if(this.isPost){
			let username = this.post('username');
      		let password = think.md5(this.post('password'));	
			
			//查询是否有用户名
			let userinfo = await this.model('or_admin').where({username:username}).find();
			
			if(think.isEmpty(userinfo)){
				return this.fail('用户名不存在！');	
			}else if(password !== userinfo.password)
			{
				return this.fail('密码错误！');
				
			}else
			{
				//根据departmentid分别赋值session类型
				let departmentinfo = await this.model('or_department').where({id:userinfo.departmentid}).find();
				1 == departmentinfo.floor?await this.session('shop_userinfo',userinfo):await this.session('or_userinfo',userinfo);
				let permission = await this.model('or_rule_admin').where({id:userinfo.groupid}).find();

				let data = {
					floor : departmentinfo.floor,
					permi : permission
				}
				return this.success(data);
			}
		}	
		return this.json({isrelogin:1});
	}

	async newsigninAction () {
		let username = this.post('username')
      	let password = think.md5(this.post('password'))
      	let machineid = this.post('machineid')

      	let userinfo = await this.model('or_admin').where({username:username}).find();
			
		if(think.isEmpty(userinfo)){
			return this.fail('用户名不存在！');	
		}else if(password !== userinfo.password)
		{
			return this.fail('密码错误！');
			
		}else
		{
			// 验证通过后进行下一步
			// 生成token
			// 机器码简单加密
			let simpleSceret = {
				machineid: machineid
			}
			// 特殊加密
			let specialSecret = {
				uid: userinfo.id,
				time: Math.round(new Date().valueOf()/1000)
			}
			const S = require('./secret.js')
			let secret = new S()
			let basetoken = secret.cipherbase64(simpleSceret) + '.' + secret.cipherbase64(specialSecret)
			let lasttoken = secret.createHmac(basetoken)
			let token = basetoken + '.' + lasttoken


			// 下面的验证还是暂时正常运作

			//根据departmentid分别赋值session类型
			let departmentinfo = await this.model('or_department').where({id:userinfo.departmentid}).find();
			1 == departmentinfo.floor?await this.session('shop_userinfo',userinfo):await this.session('or_userinfo',userinfo);
			let permission = await this.model('or_rule_admin').where({id:userinfo.groupid}).find();
			let user = {
				id: userinfo.id,
				name: userinfo.name,
				headimg: userinfo.headimg
			}
			let data = {
				floor: departmentinfo.floor,
				permi: permission,
				token: token,
				userinfo: user
			}
			return this.success(data);
		}

	}
	
	//登出
	async logoutAction(){
		
		await this.session('or_userinfo', null);
		await this.session('shop_userinfo',null);
		return this.success('退出成功！');
	}
	
	//获取七牛上传图片的验证token
	async gettokenAction(){		
		let qiniu = require("qiniu");
		//需要填写你的 Access Key 和 Secret Key
		qiniu.conf.ACCESS_KEY = this.config('qiniu.ACCESS_KEY');
		qiniu.conf.SECRET_KEY = this.config('qiniu.SECRET_KEY');
		//要上传的空间
		let bucket = this.config('qiniu.BUCKET')

		let mac = new qiniu.auth.digest.Mac(qiniu.conf.ACCESS_KEY, qiniu.conf.SECRET_KEY)
		let putPolicy = new qiniu.rs.PutPolicy({
		  scope: bucket,
		})
		let uploadToken = putPolicy.uploadToken(mac)

		let data = {'uptoken': uploadToken}
		return this.json(data)
	}
	
	//获取左侧的分类列表
	async getMenuAction(){
		let mlist = await this.model('menu').where({status:1,is_hidden:0}).select();
		return this.json(mlist);
	}

	// 获取当前用户的权限信息
	async getpermissioninfoAction(){
		let data = this.post();
		console.log(data);
		return this.fail('.....');
	}

	// 获取最新版本号
	async getversionAction(){
		let version = await this.model('config').where({id: 1}).find()
		return this.json(version)
	}

	async getexcelAction () {
		var xlsx = require('node-xlsx')
		var fs = require('fs')

		const data = [[1, 2, 3], [true, false, null, 'sheetjs'], ['foo', 'bar', new Date('2014-02-19T14:30Z'), '0.3'], ['baz', null, 'qux']];
		var buffer = xlsx.build([{name: "mySheetName", data: data}]); // Returns a buffer
		
		// fs.writeFileSync('b.xlsx', buffer, 'binary');
		//this.ctx.respond = false
		console.log(this.ctx.res)
		/*this.ctx.set('Content-Type', 'application/vnd.openxmlformats');
    	this.ctx.set("Content-Disposition", "attachment; filename=" + "Report.xlsx");
    	this.ctx.end(buffer, 'binary');*/

    	this.header('Content-Description', 'File Transfer');
	    this.header('Content-Type', 'application/csv; charset=utf-8');
	    this.header('Content-Disposition', 'attachment; filename=data.csv');
	    this.header('Expires', '0');
	    this.header('Cache-Control', 'must-revalidate');
	    this.ctx.set('Content-Type', 'application/vnd.openxmlformats')
	    this.ctx.set("Content-Disposition", "attachment; filename=o2olog.xlsx")
	    this.ctx.type = 'application/csv'
	    this.ctx.body = buffer
	    return false
	}
}